package com.dhcc.cdc.busi.service.impl;

import com.baomidou.mybatisplus.mapper.EntityWrapper;
import com.baomidou.mybatisplus.mapper.Wrapper;
import com.baomidou.mybatisplus.plugins.Page;
import com.dhcc.cdc.busi.dao.*;
import com.dhcc.cdc.busi.entity.*;
import com.dhcc.cdc.busi.service.ICdcDictionaryService;
import com.dhcc.cdc.busi.service.ICdcExpenseService;
import com.dhcc.cdc.sys.dao.CdcDataMapper;
import com.dhcc.cdc.sys.entity.CdcDataEntity;
import com.dhcc.cdc.sys.service.ICdcDataService;
import com.dhcc.core.framework.base.service.impl.BaseServiceImpl;
import com.dhcc.core.framework.util.CommonUtil;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.text.SimpleDateFormat;
import java.util.*;

/**
 * 费用表数据服务层接口
 * 
 * @ClassName: CdcExpenseServiceImpl
 * @Description: TODO
 * @author jumper
 * @date 2021-03-15 10:20:08
 */
@Service("cdcExpenseService")
public class CdcExpenseServiceImpl extends BaseServiceImpl<CdcExpenseMapper, CdcExpenseEntity> implements ICdcExpenseService {

	@Autowired
	ICdcDictionaryService dictritionSrv;
	@Autowired
	ICdcDataService dataSrv;

	@Autowired
	private CdcEpisodeMapper cdcEpisodeMapper;

	@Autowired
	private CdcDictionaryMapper cdcDictionaryMapper;

	@Autowired
	private CdcDataMapper cdcDataMapper;

	@Autowired
	private CdcDictypeMapper cdcDictypeMapper;

	@Autowired
	private CdcExpitemMapper cdcExpitemMapper;
	
	@Autowired
    private CdcUserMapper cdcUserMapper;
	
	@Override
	public List<CdcExpenseEntity> page(Page<CdcExpenseEntity> page, Map<String, Object> map) {
		return warpExpense(this.baseMapper.page(page, map));
	}
	@Override
	public List<CdcExpenseEntity> list(Map<String, Object> map) {
		return this.baseMapper.list(map);
	}

	public List<CdcExpenseEntity> warpExpense(List<CdcExpenseEntity> list){
		Map<Long, Object> cacheDic = new HashMap<>();
		for(CdcExpenseEntity expense:list){
			if(expense.getBusExpenseTypeId()!=null){
				if(cacheDic.containsKey(expense.getBusExpenseTypeId())){
					expense.setBusExpenseType((CdcDictionaryEntity) cacheDic.get(expense.getBusExpenseTypeId()));
				}else{
					CdcDictionaryEntity expenseType = this.dictritionSrv.selectById(expense.getBusExpenseTypeId());
					expense.setBusExpenseType(expenseType);
					cacheDic.put(expense.getBusExpenseTypeId(),expenseType);
				}
			}else{
				expense.setBusExpenseType(new CdcDictionaryEntity());
			}
			if(expense.getDataId()!=null){
				if(cacheDic.containsKey(expense.getDataId())){
					expense.setData((CdcDataEntity) cacheDic.get(expense.getDataId()));
				}else{
					CdcDataEntity data = this.dataSrv.selectById(expense.getDataId());
					expense.setData(data);
					cacheDic.put(expense.getDataId(), data);
				}
			}else{
				expense.setData(new CdcDataEntity());
			}
		}


		return list;

	}
	@Override
	public String handleXmlData(String dataStr) {

		SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm:ss");
		Document doc = null;
		try {
			doc = DocumentHelper.parseText(dataStr); // 将字符串转为XML
			Element rootElt = doc.getRootElement(); // 获取根节点
			String episodeid = rootElt.elementTextTrim("episodeid"); // 就诊记录
			String costsstr = rootElt.elementTextTrim("costs"); // 总费用
			String paysstr = rootElt.elementTextTrim("pays"); // 自付费用
			String busexpensetypecode = rootElt.elementTextTrim("busexpensetypecode"); // 费用类型
			String busexpensetypedesc = rootElt.elementTextTrim("busexpensetypedesc"); // 费用类型
			String updatetimestr = rootElt.elementTextTrim("updatetime"); //更新时间
            String updateuserid = rootElt.elementTextTrim("updateuserid"); //更新人
			String opercode = rootElt.elementTextTrim("opercode"); // 操作码
			CdcDataEntity cdcDataEntity = new CdcDataEntity();
			cdcDataEntity.setCode("ExpData");
			cdcDataEntity.setIsActive(1);
			cdcDataEntity = cdcDataMapper.selectOne(cdcDataEntity);
			Long dataId = cdcDataEntity.getId();
			//获取basedataId
			CdcDataEntity cdcDataEntityBase = new CdcDataEntity();
			cdcDataEntityBase.setCode("HisBase");
			cdcDataEntityBase.setIsActive(1);
			cdcDataEntityBase = cdcDataMapper.selectOne(cdcDataEntityBase);
    		Long basedataId = cdcDataEntityBase.getId();
			CdcExpenseEntity exp = new CdcExpenseEntity();
			// 获取episodeid
			CdcEpisodeEntity cdcEpisodeEntity = new CdcEpisodeEntity();
			cdcEpisodeEntity.setXcode(episodeid);
			cdcEpisodeEntity = cdcEpisodeMapper.selectOne(cdcEpisodeEntity);// 就诊信息没在库中？？？
			Long epsid = cdcEpisodeEntity.getId();
			exp.setEpisodeId(epsid);
			if(CommonUtil.isNotEmpty(updatetimestr)) {
        		Date updatetime = sdf.parse(updatetimestr);
        		exp.setUpdateDate(updatetime);
        	}
        	//获取更新人
        	if(CommonUtil.isNotEmpty(updateuserid)) {
        		CdcUserEntity cdcUserEntity = new CdcUserEntity();
        		cdcUserEntity.setXcode(updateuserid);
        		cdcUserEntity.setDataId(basedataId);
        		cdcUserEntity.setIsActive(1);
        		cdcUserEntity = cdcUserMapper.selectOne(cdcUserEntity);
        		//判断人员存在不存在
        		Long updateuser = null;
        		if(CommonUtil.isEmpty(cdcUserEntity)) {//不存在  保存到用户表里面
        			cdcUserEntity = new CdcUserEntity();
        			cdcUserEntity.setXcode(updateuserid);
            		cdcUserEntity.setIsActive(1);
        			cdcUserEntity.setCode("newuser"+updateuserid);
        			cdcUserEntity.setName("newuser"+updateuserid);
            		cdcUserEntity.setDataId(basedataId);
            		//保存用户
            		cdcUserMapper.insert(cdcUserEntity);
            		updateuser = cdcUserEntity.getId();
        		}else {
        			updateuser = cdcUserEntity.getId();
        		}
        		exp.setUpdateBy(updateuser);
        	}
			if ("1".equals(opercode)) {// 保存/修改
				if(CommonUtil.isNotEmpty(costsstr)) {
					//Float costs = Float.valueOf(costsstr);
					BigDecimal costs = new BigDecimal(costsstr);
					costs = costs.setScale(2, BigDecimal.ROUND_HALF_UP); //四舍五入
					exp.setCosts(costs);
            	}
				if(CommonUtil.isNotEmpty(paysstr)) {
					//Float pays = Float.valueOf(paysstr);
					BigDecimal pays = new BigDecimal(paysstr);
					pays = pays.setScale(2, BigDecimal.ROUND_HALF_UP); //四舍五入
            		exp.setPays(pays);
            	}
				// 获取ID
				if (CommonUtil.isNotEmpty(busexpensetypecode)) {
					CdcDictypeEntity cdcDictypeEntity = new CdcDictypeEntity();
					cdcDictypeEntity.setCode("bus_expense_type");
					cdcDictypeEntity.setIsActive(1);
					cdcDictypeEntity = cdcDictypeMapper.selectOne(cdcDictypeEntity);
					Long dicexpensetypeId = cdcDictypeEntity.getId();
					// 如果没有对应ID就要插入
					CdcDictionaryEntity cdcDictionaryEntity = new CdcDictionaryEntity();
					cdcDictionaryEntity.setDictypeId(dicexpensetypeId);
					cdcDictionaryEntity.setCode(busexpensetypecode);
					cdcDictionaryEntity.setIsActive(1);
					cdcDictionaryEntity = cdcDictionaryMapper.selectOne(cdcDictionaryEntity);
					// 判断字典存在不存在
					Long busexpensetypeid = null;
					if (CommonUtil.isEmpty(cdcDictionaryEntity)) {// 不存在 保存到字典表里面
						cdcDictionaryEntity = new CdcDictionaryEntity();
						cdcDictionaryEntity.setDictypeId(dicexpensetypeId);
						cdcDictionaryEntity.setCode(busexpensetypecode);
						cdcDictionaryEntity.setDescription(busexpensetypedesc);
						cdcDictionaryEntity.setIsActive(1);
						// 保存字典
						cdcDictionaryMapper.insert(cdcDictionaryEntity);
						busexpensetypeid = cdcDictionaryEntity.getId();
					} else {
						busexpensetypeid = cdcDictionaryEntity.getId();
					}
					exp.setBusExpenseTypeId(busexpensetypeid);
				}
				exp.setDataId(dataId);
				exp.setIsActive(1);
			}else {
				exp.setIsActive(0);
			}
			// 先判断是不是有该对象
			Wrapper<CdcExpenseEntity> wrapper = new EntityWrapper<CdcExpenseEntity>();
			wrapper.eq("episode_id", exp.getEpisodeId());
			wrapper.eq("data_id", dataId);
			int count = this.selectCount(wrapper);
			if (count > 0) {
				this.update(exp, wrapper);
			} else {
				this.insert(exp);
			}
			Element eleexpItems = rootElt.element("expitems"); // 获取根节点
			Iterator<Element> iter = eleexpItems.elementIterator("expitem"); // 获取根节点下的子节点expitem
			// 遍历expitem节点
			while (iter.hasNext()) {
				Element expitemEle = iter.next();
				String code = expitemEle.elementTextTrim("code"); // 代码
				String description = expitemEle.elementTextTrim("description"); // 描述
				String coststr = expitemEle.elementTextTrim("cost"); // 报告ID
				String expensedatestr = expitemEle.elementTextTrim("expensedate"); // 费用日期
				// 先保存报告 ---再保存检验结果
				CdcExpitemEntity expitem = new CdcExpitemEntity();
				expitem.setExpenseId(epsid);
				expitem.setCode(code);
				if(CommonUtil.isNotEmpty(updatetimestr)) {
            		Date updatetime = sdf.parse(updatetimestr);
            		expitem.setUpdateDate(updatetime);
            	}
            	//获取更新人
            	if(CommonUtil.isNotEmpty(updateuserid)) {
            		CdcUserEntity cdcUserEntity = new CdcUserEntity();
            		cdcUserEntity.setXcode(updateuserid);
            		cdcUserEntity.setDataId(basedataId);
            		cdcUserEntity.setIsActive(1);
            		cdcUserEntity = cdcUserMapper.selectOne(cdcUserEntity);
            		//判断人员存在不存在
            		Long updateuser = null;
            		if(CommonUtil.isEmpty(cdcUserEntity)) {//不存在  保存到用户表里面
            			cdcUserEntity = new CdcUserEntity();
            			cdcUserEntity.setXcode(updateuserid);
                		cdcUserEntity.setIsActive(1);
            			cdcUserEntity.setCode("newuser"+updateuserid);
            			cdcUserEntity.setName("newuser"+updateuserid);
                		cdcUserEntity.setDataId(basedataId);
                		//保存用户
                		cdcUserMapper.insert(cdcUserEntity);
                		updateuser = cdcUserEntity.getId();
            		}else {
            			updateuser = cdcUserEntity.getId();
            		}
            		expitem.setUpdateBy(updateuser);
            	}
				if ("1".equals(opercode)) {// 保存/修改
					if(CommonUtil.isNotEmpty(description)) {
						expitem.setDescription(description);
					}
					if(CommonUtil.isNotEmpty(coststr)) {
						//Float cost = Float.valueOf(coststr);
						BigDecimal cost = new BigDecimal(coststr);
						cost = cost.setScale(2, BigDecimal.ROUND_HALF_UP); //四舍五入
	            		expitem.setCost(cost);
	            	}
					if(CommonUtil.isNotEmpty(expensedatestr)) {
	            		Date expensedate = sdf.parse(expensedatestr);
	            		expitem.setExpenseDate(expensedate);
	            	}
					expitem.setIsActive(1);
				} else {
					expitem.setIsActive(0);
				}
				// 先判断是不是有该对象
				Wrapper<CdcExpitemEntity> wrapperitem = new EntityWrapper<CdcExpitemEntity>();
				wrapperitem.eq("expense_id", expitem.getExpenseId());
				wrapperitem.eq("code", expitem.getCode());
				wrapperitem.eq("data_id", dataId);
				int countitem = this.selectCount(wrapper);
				if (countitem > 0) {
					cdcExpitemMapper.update(expitem, wrapperitem);
				} else {
					cdcExpitemMapper.insert(expitem);
				}
			}
		} catch (DocumentException e) {
			e.printStackTrace();
			return "<response><status>0</status><message>" + e.getMessage() + "</message></response>";
		} catch (Exception e) {
			e.printStackTrace();
			return "<response><status>0</status><message>" + e.getMessage() + "</message></response>";
		}
		return "<response><status>1</status><message>ok</message></response>";
	}

}
